package middleware

import (
	"net/http"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/rs/zerolog/log"
)

// HTTPLoggerConfig HTTP日志中间件配置
type HTTPLoggerConfig struct {
	// 是否记录成功的请求（2xx状态码）
	LogSuccess bool
	// 慢请求阈值，超过此时间的请求会被记录为warn
	SlowRequestThreshold time.Duration
	// 跳过记录的路径
	SkipPaths map[string]bool
}

// DefaultHTTPLoggerConfig 默认配置
func DefaultHTTPLoggerConfig() HTTPLoggerConfig {
	return HTTPLoggerConfig{
		LogSuccess:           false,
		SlowRequestThreshold: 2 * time.Second, // 降低到2秒
		SkipPaths: map[string]bool{
			"/health":  true,
			"/metrics": true,
		},
	}
}

// HTTPLogger 自定义HTTP日志中间件
func HTTPLogger() echo.MiddlewareFunc {
	return HTTPLoggerWithConfig(DefaultHTTPLoggerConfig())
}

// HTTPLoggerWithConfig 带配置的HTTP日志中间件
func HTTPLoggerWithConfig(config HTTPLoggerConfig) echo.MiddlewareFunc {
	return echo.MiddlewareFunc(func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			// 检查是否跳过此路径
			reqPath := c.Request().URL.Path
			if config.SkipPaths[reqPath] {
				return next(c)
			}

			start := time.Now()
			err := next(c)
			duration := time.Since(start)

			// 获取响应信息
			req := c.Request()
			res := c.Response()
			status := res.Status

			// 修复状态码获取问题
			if err != nil && status == 200 {
				if he, ok := err.(*echo.HTTPError); ok {
					status = he.Code
				} else {
					status = http.StatusInternalServerError
				}
			}

			// 获取客户端IP
			clientIP := c.RealIP()
			if clientIP == "" {
				clientIP = c.Request().RemoteAddr
			}

			// 构建日志事件
			logEvent := log.With().
				Str("method", req.Method).
				Str("uri", req.RequestURI).
				Int("status", status).
				Int64("latency_ms", duration.Milliseconds()).
				Str("client_ip", clientIP)

			// 添加请求ID（如果存在）
			if reqID := c.Response().Header().Get(echo.HeaderXRequestID); reqID != "" {
				logEvent = logEvent.Str("request_id", reqID)
			}

			logger := logEvent.Logger()

			// 根据状态码和响应时间决定日志级别
			if err != nil {
				logger.Error().Err(err).Msg("请求处理出错")
			} else if status >= 500 {
				logger.Error().Msg("服务器错误")
			} else if status >= 400 {
				logger.Warn().Msg("客户端错误")
			} else if duration > config.SlowRequestThreshold {
				logger.Warn().Msg("慢请求")
			} else if config.LogSuccess && status >= 200 && status < 300 {
				logger.Info().Msg("请求成功")
			}

			return err
		}
	})
}
